package com;

import com.example.common.constant.PlainToken;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.parser.Authorization;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.example.common.constant.Constant.JSON_TOKEN;

/**
 * 用于将网关中的明文 json-token 转换为 对应的权限对象
 * @author 罗俊华
 * @date 2022/3/14 - 5:19 下午
 */
@Slf4j
@Service
public class TokenAuthorizationFilter extends OncePerRequestFilter {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

//        从请求头中取出 gateway 放入的明文 token
        String jsonToken = request.getHeader(JSON_TOKEN);

        if(StringUtils.hasLength(jsonToken)){
            return;
        }

//        从请求头中解析出 明文的权限信息
        JsonNode rootNode = objectMapper.readTree(jsonToken);

        OAuth2Request storedRequest = objectMapper.readValue(rootNode.get("storedRequest").asText(), OAuth2Request.class);

        JsonNode userAuthenticationNode = rootNode.get("userAuthentication");

//         objectMapper.readValue(userAuthenticationNode.asText(), OAuth2Request.class);

        Authentication authentication = new OAuth2Authentication(
                storedRequest,
                new OAuth2Authentication(storedRequest,null)

        );

//        authentication.se

        SecurityContext securityContext = SecurityContextHolder.createEmptyContext();

        securityContext.setAuthentication(authentication);


        SecurityContextHolder.setContext(securityContext);


        filterChain.doFilter(request,httpServletResponse);
    }
}
